﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using DTO;

namespace DAO
{

	public class CustomersDAO:IData
 	{
		public CustomersDAO(String myconnecString) : base(myconnecString) { }

		public  int OnSubmit(Customers item, int t) {
			 return connec.ExecuteNonQuery("sp_Customers", CommandType.StoredProcedure,new SqlParameter("@flag", t),
				 new SqlParameter("@" + Customers.c_id, item.id), new SqlParameter("@" + Customers.c_userId, item.userId),
				 new SqlParameter("@" + Customers.c_fullname, item.fullname), new SqlParameter("@" + Customers.c_address, item.address),
				 new SqlParameter("@" + Customers.c_phone, item.phone), new SqlParameter("@" + Customers.c_isActive, item.isActive)); 
		}

		public  Customers GetItem(IDataReader dr)
		{
			Customers obj = new Customers();
			obj.id = Convert.ToInt64(dr[Customers.c_id]);
			obj.userId = Convert.ToInt64(dr[Customers.c_userId]);
			obj.fullname = Convert.ToString(dr[Customers.c_fullname]);
			obj.address = Convert.ToString(dr[Customers.c_address]);
			obj.phone = Convert.ToString(dr[Customers.c_phone]);
			obj.isActive = Convert.ToInt32(dr[Customers.c_isActive]);
			return obj;
		}

        private List<Customers> GetAll(String strSQL, CommandType commandtype)
        {
            List<Customers> list = new List<Customers>();
            SqlConnection connection = connec.Connection;
            SqlCommand command = new SqlCommand();
            command.CommandType = commandtype;
            command.CommandText = strSQL;
            command.Connection = connection;
            connection.Open();
            SqlDataReader reader;
            using (reader = command.ExecuteReader(CommandBehavior.CloseConnection))
            {
                while (reader.Read())
                {
                    list.Insert(0, GetItem(reader));
                }
                reader.Close();
            }
            connection.Close();
            return list;
        }
		public  List<Customers> GetAll()
		{
			return GetAll("select * from " + Customers.b_Customers, CommandType.Text);
		}

		public  Customers GetItemById(object id)
		{
			 return this.GetAll().FirstOrDefault(x => x.id == (long)id);
		}

	}

 }
